<?php

/**
 * MARKETOOLS 跟踪API PHP Version
 * ============================================================================
 * 版权所有 2007-2010 海南推广易科技有限公司，并保留所有权利。
 * 网站地址: http://www.marketools.cn；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: easelify $
 * $Id: track.php 2010/6/21 2011/3/30 easelify $
 */
error_reporting(E_ALL & ~E_NOTICE);

/**
 * MT推广易主程序路径
 *
 * @since 4.0
 * 末尾不要加 "/"，例如：http://union.yourdomain.com
 */
define('MT_API_BASEURL', 'http://union.dreams-travel.com');


/**
 * MT API安全码
 *
 * @since 4.0
 * 请确保此值和您MT推广易程序目录 /sttings/settings.php 中定义的 API_SECURITYCODE 常量一致
 *
 */
define('MT_API_SECURITYCODE', 'dec381e6c53f9tabb87eb76db3f72f69');


/* * *****************************
 * 获取跟踪令牌
 *
 * @since 4.0
 * 其他程序如ASP，JSP等，请参照此函数获取安全码
 * 其中带的参数 cmd: 方法，securitycode: 预先设定好的安全验证码
 * ***************************** */

function Marketools_GetTrackToken() {
    return @file_get_contents(MT_API_BASEURL . '/api/getoken.php?cmd=step1&securitycode=' . MT_API_SECURITYCODE);
}

/* * *****************************
 * 生成PHP跟踪请求地址的函数
 *
 * @since 4.0
 * ***************************** */

function Marketools_GetTrackRequestAddress($params, $basicparams = array()) {
    $gateway = MT_API_BASEURL . '/scripts/sale_hide.php?';
    if (empty($basicparams)) {
        $basicparams = array(
            'lid' => '',
            'trackingMethod' => 6,
            'fsc' => $_COOKIE['POSTAff2Cookie'],
            'fstc' => $_COOKIE['POSTAff2TimeCookie'],
            'forc' => $_COOKIE['PAPR_0']
        );
    }
    foreach ($_COOKIE as $key => $value) {
        $url .= '&incookie_' . $key . '=' . $value;
    }
    $pms = array_merge($basicparams, $params);
    foreach ($pms as $key => $value) {
        $url .= '&' . $key . '=' . $value;
    }
    return $gateway . $url;
}

/* * *****************************
 * 生成PHP跟踪请求地址基本参数
 *
 * @since 4.0
 * ***************************** */

function Marketools_GetTrackBasicParams() {
    $params = array(
        'lid' => '',
        'trackingMethod' => 6,
        'fsc' => $_COOKIE['POSTAff2Cookie'],
        'fstc' => $_COOKIE['POSTAff2TimeCookie'],
        'forc' => $_COOKIE['PAPR_0']
    );
    foreach ($_COOKIE as $key => $value) {
        $params['incookie_' . $key] = $value;
    }
    return serialize($params);
}

/* * ***********************************
 * 销售通知API，注意键值大小写敏感
 *
 * @since 4.1
 * ********************************** */

function Marketools_SaleNotify($params) {
    $u = parse_url(MT_API_BASEURL);
    $port = is_numeric($u['port']) ? $u['port'] : '80';
    Marketools_SendHttpRequest($u['scheme'], $u['host'], $port, $u['path'] . '/scripts/sale_hide.php', $params);
}

/* * ***********************************
 * 退款通知API，注意键值大小写敏感
 *
 * @since 4.1
 * ********************************** */

function Marketools_RefundNotify($orderid) {
    if (empty($orderid))
        return false;
    $token = Marketools_GetTrackToken();
    $params = array(
        'orderid' => $orderid,
        'token' => $token
    );
    $u = parse_url(MT_API_BASEURL);
    $port = is_numeric($u['port']) ? $u['port'] : '80';
    Marketools_SendHttpRequest($u['scheme'], $u['host'], $port, $u['path'] . '/scripts/refundnotify.php', $params);
}

/* * *****************************
 * 绑定客户API
 *
 * @since 4.0
 *
 * 传入参数说明
 *     $params = array(
 *        'action'=>bind/unbind,     //绑定，解绑
 *        'outuserid'=>String,       //外部用户ID，多个ID请用英文逗号(,)分开
 *        'outusername'=>String      //外部用户名
 *     );
 *
 *     $type = js/socket             //跟踪触发方式

 * 返回信息含义
 *    <!-- //0 -->                   //未知方法
 *    <!-- //1 -->                   //绑定功能未开启
 *    <!-- //2 -->                   //参数错误
 *    <!-- //3 -->                   //推广员不存在
 *    <!-- //4 -->                   //该客户已经绑定了推广员
 *    <!-- //5 -->                   //令牌错误
 *    <!-- //6 -->                   //绑定失败
 *    <!-- //7 -->                   //绑定成功
 *    <!-- //8 -->                   //解除绑定成功
 * ***************************** */

function Marketools_BindingCustomer($params, $type = 'js') {
    $params['affid'] = Marketools_GetAffiliateIdFromCookie();
    if (empty($params['affid']) && $params['action'] == 'bind') {
        return '<!-- //2 -->';
    }

    $params['token'] = Marketools_GetTrackToken();
    $gateway = MT_API_BASEURL . '/api/bindingclient.php?';
    foreach ($params as $key => $value) {
        $gateway .= $key . '=' . $value . '&';
    }

    if ($type == 'js') {
        return '<script type="text/javascript" src="' . $gateway . '"></script>';
    } elseif ($type == 'socket') {
        return @file_get_contents($gateway);
    }
}

/* * *****************************
 * 绑定推广员API
 *
 * @since 4.0
 *
 * 传入参数说明：
 *     $outuserid //外部用户ID
 *     $type = js/socket //跟踪触发方式

 * 返回 VOID
 *   string  //推广员ID
 * ***************************** */

function Marketools_BindingAffiliate($outuserid, $type) {
    $type = $type == '' ? 'js' : $type;
    $params['action'] = 'getaffiliate';
    $params['token'] = Marketools_GetTrackToken();
    $params['affid'] = Marketools_GetAffiliateIdFromCookie();
    $params['outuserid'] = $outuserid;
    $params['method'] = $type;
    $params['cookie'] = $_COOKIE['POSTAff2Cookie'];

    $gateway = MT_API_BASEURL . '/api/bindingclient.php?';
    foreach ($params as $key => $value) {
        $gateway .= $key . '=' . $value . '&';
    }

    if ($type == 'js') {
        return
                '<script type="text/javascript" src="' . $gateway . '"></script>' . '
    <script type="text/javascript">
    <!--
    if(mt_aff_cover) {
        var today = new Date();
        var expires = new Date();
        expires.setTime(today.getTime()+1000*60*60*24*365);
        document.cookie = "POSTAff2Cookie="+escape(mt_aff_cover)+";expires="+expires.toGMTString();
    }
    -->
    </script>'
        ;
    } elseif ($type == 'socket') {
        $mt_aff_cover = @file_get_contents($gateway);
        if ($mt_aff_cover) {
            setcookie('POSTAff2Cookie', $mt_aff_cover, 2 * time());
        }
    }
}

/* * *****************************
 * 获取COOKIE里的推广员ID
 *
 * @since 4.0
 * ***************************** */

function Marketools_GetAffiliateIdFromCookie() {
    $r = explode('_', $_COOKIE['POSTAff2Cookie']);
    return $r[0];
}

/* * *****************************
 * 发送HTTP POST请求
 *
 * @since 4.1
 * ***************************** */

function Marketools_SendHttpRequest($type, $host, $port = '80', $path = '/', $data = array(), &$response = '') {
    $_err = 'lib sockets::' . __FUNCTION__ . '(): ';
    switch ($type) {
        case 'http': $type = '';
        case 'ssl': continue;
        default: die($_err . 'bad $type');
    } if (!ctype_digit($port))
        die($_err . 'bad port');
    if (!empty($data)) {
        foreach ($data as $k => $v) {
            $str .= urlencode($k) . '=' . urlencode($v) . '&';
        }
    }
    if (!empty($_COOKIE)) {
        foreach ($_COOKIE as $k => $v) {
            $str .= urlencode('incookie_'.$k) . '=' . urlencode($v) . '&';
        }
    }
    $str = substr($str, 0, -1);
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout = 60);
    if (!$fp)
        die($_err . $errstr . $errno); else {
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");
        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($str) . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $str . "\r\n\r\n");
        if ($response)
            while (!feof($fp)) {
                $response .= fgets($fp, 4096);
            }
        fclose($fp);
    }
}

?>